<?php

namespace app\api\controller\v1;


use app\admin\controller\Zlog;
use app\common\controller\Api;
use addons\adszone\library\Adszone;
use app\common\library\Auth;
use app\common\library\Utils;
use app\common\logic\ChatLogic;
use app\common\logic\ChatManagerLogic;
use app\common\logic\CourseLogic;
use app\common\model\chat\ChatRoom;
use app\common\model\course\Chapter;
use app\common\model\course\Course;
use app\common\model\course\Order;
use think\Db;
use think\Exception;

/**
 * 问答控制器
 */
class Chat extends Api
{
    protected $noNeedLogin = ['test','history','banners','checkffmpeg','checkInfo','joinin','getChatConfig'];
    protected $noNeedRight = '*';

    public function banners() {
        $pic = new Adszone();
        $tag = $this->request->post("banner_type",'chat_banner');//图片类别chat_banner：直播室顶部图；chat_series:直播系列主图; chat_course：直播课程主图；
        $list = $pic->getAdsByMark($tag,ORG_CATE_ID);
        $this->success('轮播图', $list);
    }

    //获取往期直播 首页固定4条数据
    public function history() {
        $chat = new ChatLogic();
        $list = $chat->getHistory([], 4);//往期直播

        $this->success('往期直播', $list);
    }

    //查看更多
    public function pageHistory() {
        $chat = new ChatLogic();
        $list = $chat->getHistory();//往期直播

        $this->success('往期直播', $list);
    }

    /*
     * 获取直播课程章节序号
     * */
    public function getHistoryChapter() {
        $course_id = input('course_id/d', 0);
        $courseLogic = new CourseLogic();
        $list = $courseLogic->getChapters($course_id);

        $this->success('章节列表', $list);
    }
    /*
     * 获取直播预告
     * 所有未结束的直播
     * */
    public function getBefore() {
        $chatLogic = new ChatLogic();
        $list = $chatLogic->getChapter([], $this->auth->getUser());
        $appid = config('config')['chat']['app_id']?:'wx2e00a5ec9f4c5999';
        $data = [
            'list'=>$list,
            'appid'=>$appid
        ];
        $this->success('直播列表', $data);
    }

    //获取往期直播详情
    public function getChapterHistory() {
        $id = input('id/d', 0);
        if (!$id) {
            $this->error('章节id必须传递');
        }

        $info = Chapter::get($id);
        if (!$info) {
            $this->error('获取课程信息错误');
        }
        //查看课程是否购买
        $where['user_id'] = UID;
        $where['learn_course_id'] = $info['edu_learn_course_id'];
        $where['type'] = 1;
        $res = (new Order())->where($where)->count();
        $course = Course::get($info['edu_learn_course_id']);
        if ($course['price'] != 0 && $res < 1) {
            $this->error('请先购买课程');
        }

        //获取直播室信息
        $room = ChatRoom::get(['chapter' => $id]);
        if (!$room  || $room['type'] != 3) {
            $info['room'] = 0 ;//直播还未结束
        } else {
            $info['room'] = 1 ;  //直播结束
        }

        $info['talk_name'] = \app\common\model\chat\ChatUser::where(['id'=> $room['talk_id']])->value('nickname');
        $info['chat_time'] = Utils::time_format($room['start_time']);
        $this->success('章节详情', $info);
    }
    /*
     * 直播详情
     * */
    public function detail() {
        $id = input('id', 0);
        $chatLogic = new ChatLogic();
        $info = $chatLogic->getChatDetail($id, $this->auth->getUser());
        $this->success('课程详情', $info);
    }

    //获取聊天人头像 角色
    public function getAuth() {
        $open_id = input('open_id', '');
        $id = input('id', '');  //直播室id
        if (!$open_id || !$id) {
            $this->error('参数错误');
        }
        $chatLogic = new ChatLogic();

        $auth = $chatLogic->getAuth($id, $open_id);
        $this->success('权限', $auth);
    }

    //获取预录入文字和图片
    public function beforeMsg() {
        $text = Db::name('chat_file')->where(['user_id'=> UID, 'type' => 0,'org_cate_id'=>ORG_CATE_ID])->select();
        $file = Db::name('chat_file')->where(['user_id'=> UID, 'type' => 1,'org_cate_id'=>ORG_CATE_ID])->select();

        $this->success('预录入', [
           'text' => $text,
           'file' => $file
        ]);
    }

    //保存
    public function saveBefore() {
        $type = input('type/d', 0);
        $text = input('content', '');

        $data = [
            'user_id' => UID,
            'org_cate_id' => ORG_CATE_ID,
            'type'    => $type
        ];
        if ($type == 0) {
            $data['text'] = $text;
        } else {
            $data['image'] = $text;
        }

        $res = Db::name('chat_file')->insert($data);
        if (!$res) {
            $this->error('保存失败');
        }

        $this->success('保存成功');
    }

    //保存
    public function delBefore() {
        $id = input('id', 0);
        $res = Db::name('chat_file')->where('id', $id)->delete();
        if (!$res) {
            $this->error('保存失败');
        }

        $this->success('保存成功');
    }

    public function test() {
        $chat = new ChatLogic();
        $chat->videos();
    }

    public function text()
    {
        $list = Db::name('chat_text')->select();
        $this->success('弹幕', $list);
    }

    public function checkInfo()
    {
        $appid = $this->request->post('appid')?:'';
        $timestamp = $this->request->post('timestamp')?:'';
        $signature = $this->request->post('signature')?:'';
        $secret = config('config')['chat']['secret']?:'huiyijia20190901';
        $str = sha1($appid.$timestamp.$secret);
        $token = $this->request->post('token') ? $this->request->post('token') : '';
        if(empty($token)){
            $res = ["errcode"=>1101,"errmsg"=>"User authorize fail."];
            return json_encode($res);
        }
        $this->auth = Auth::instance();
        $this->auth->init($token);
        if ($this->auth->isLogin()) {
            $user = $this->auth->getUser();
            if($str == $signature){
//                $openid = Db::name('third')->where('user_id', $user['id'])->value('openid');
                $res = ["errcode"=>0,"errmsg"=>"ok",'openid'=>$user['openid']];
                return json_encode($res);
            }else{
                $res = ["errcode"=>1101,"errmsg"=>"User authorize fail."];
                return json_encode($res);
            }
        } else {
            $res = ["errcode"=>1101,"errmsg"=>"User authorize fail."];
            return json_encode($res);
        }
    }

    public function getChatConfig()
    {
        $data['app_id'] = config('config')['chat']['app_id']?:'wx2e00a5ec9f4c5999';
        $data['secret'] = config('config')['chat']['secret']?:'huiyijia20190901';
        return json_encode($data);
    }

    /*
     * 开启、关闭聊天室
     */
    public function chatroomdo()
    {
        $room_id = $this->request->post('room_id');
        $type = $this->request->post('type')?:1;//1开启 2关闭
        if(empty($room_id)){
            $this->error('缺少直播室id！');
        }
        if(!in_array($type, array(1,2))){
            $this->error('类型错误！');
        }
        $chat = new ChatManagerLogic();

        $res = $chat->close($room_id);

        if($res){
            Db::name('chat_room')->where(['room_id'=> $room_id])->update(['type'=>3,'end_time'=>time()]);
        }
        if($res){
            $this->success('操作成功！');
        }else{
            $this->error('操作失败！');
        }

    }

    public function getChatInfo()
    {
        $course_id = $this->request->post('course_id');
        if(empty($course_id)){
            $this->error('缺少课程id！');
        }
        $info = Db::name('chat_info')->where('edu_learn_course_id', $course_id)->field('*')->select();
        if($info){
            foreach($info as &$val){
                $val['text'] = unserialize($val['text']);
                $val['text'] = json_encode($val['text']);
            }
        }
        if($info){
            $this->success('', $info);
        }else{
            $this->error('暂无数据');
        }
    }

    public function getwebsocket()
    {
        $room_id = $this->request->post('room_id');
        if(empty($room_id)){
            $this->error('缺少直播室id！');
        }
        $course_id = $this->request->post('course_id');
        if(empty($course_id)){
            $this->error('缺少课程id！');
        }
        $info = $this->request->post('info');
        $info = htmlspecialchars_decode($info);
        $info = html_entity_decode($info);
        $info = stripslashes($info);
        $data = json_decode($info, true);
        if($data){
            $insert['room_id'] = $room_id;
            $insert['edu_learn_course_id'] = $course_id;
            $insert['text'] = serialize($data);
            $insert['createtime'] = time();
            $id = Db::name('chat_info')->insertGetId($insert);
            $voice = array();
            foreach($data as $val){
                if($val['type'] == 2){
                    $voice[] = $val['content']['url'];
                }
            }
            if(!empty($voice)){
                $chat = new ChatManagerLogic();
                $res = $chat->joinvoice($id, $voice, $room_id);
                if($res){
                    $this->success('数据保存成功!');
                }else{
                    Db::name('chat_info')->where('id', $id)->delete();
                    $this->error('数据保存失败！');
                }
            }
            $this->success('数据保存成功!');
        }
        $this->error('数据保存失败！');
    }

}
